//
//  ViewController.m
//  iOSNetworkLessonFive
//
//  Created by lcy on 16/1/18.
//  Copyright © 2016年 lcy. All rights reserved.
//

#import "ViewController.h"

@interface ViewController () <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSURLSessionDelegate>

@property (nonatomic, strong) NSMutableData *myData;

@end

@implementation ViewController

- (NSMutableData *)myData
{
    if(_myData == nil)
    {
        self.myData = [NSMutableData data];
    }
    return _myData;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    // 1.获取请求网址
    NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?"];
    
    // 2.封装请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];  // post
    
    // 设置请求方式
    [request setHTTPMethod:@"POST"];
    
    // 设置请求体(会把请求的数据转成data,达到用户信息保密的目的)
    NSData *data = [@"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" dataUsingEncoding:NSUTF8StringEncoding];
    
    [request setHTTPBody:data];
    
//    [NSURLConnection connectionWithRequest:request delegate:self];
    
    // 创建NSURLSession
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
//    NSURLSession *session = [NSURLSession sharedSession];
//    
//    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:
                                  ^(NSData *data, NSURLResponse *response, NSError *error) {
                                      // 获取数据
                                      NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
                                      
                                      NSLog(@"%@", dic);
                                  }];
    
    [task resume];
}

// 在协议的方法中可以完成各种各样的回调动作，如身份验证、完成任务后的动作、错误处理和后台任务完成的动作等。委托方法指定在NSURLSession中一定数量的字节传输使用int64_t类型的参数。
- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
{
    
}


- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler
{
    
}



- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session NS_AVAILABLE_IOS(7_0)
{
    
}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if(error)
    {
        NSLog(@"%@", [error localizedDescription]);
    }
}

// 收到服务器响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"收到服务器响应");
}

// 可能多次调用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.myData appendData:data];
    NSLog(@"收到数据");
}


// 完成数据接收
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSError *error = nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.myData options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];
    
    if(error)
    {
        NSLog(@"%@", [error localizedDescription]);
    }
    
    NSLog(@"%@", dic);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
